package reports

import (
	"bytes"
	"fmt"
	"strings"
	"time"

	"shqsoft.cn/pas3ui/base"
)

func createDataChangeAnalysis(repConf *Config, tName string, paramVals map[string]interface{}) (err error) {
	if repConf.DataSource.DFTable == "" {
		err = fmt.Errorf("生成报表%s的ChangeAnalysis出错，DataSource.DFTable不能为空", repConf.Name)
		return
	}
	if repConf.DataSource.TmpTableName == "" {
		err = fmt.Errorf("生成报表%s的ChangeAnalysis出错，DataSource.TmpTableName不能为空", repConf.Name)
		return
	}
	var dbHelp *DataBase
	dbHelp, err = NewDataBase(tName, repConf)
	if err != nil {
		return
	}
	var exists bool
	exists, err = dbHelp.tableTxists()
	if err != nil {
		return
	}
	if exists {
		return
	}
	reptLock.Lock(tName)
	defer reptLock.Unlock(tName)
	var date time.Time
	if paramVals["date"] != nil {
		date = paramVals["date"].(time.Time)
	}
	if date.IsZero() {
		err = fmt.Errorf("生成报表%s的LineColumnData出错，参数date不能为空", repConf.Name)
		return
	}
	var where, colName string
	colName, where, err = parseLineColumnParams(repConf, paramVals)
	curDate := date.Format("2006-01-02")
	srdate := date.AddDate(0, 0, -1).Format("2006-01-02")
	symdate := time.Date(date.Year(), date.Month(), 1, 0, 0, 0, 0, time.Local).AddDate(0, 0, -1).Format("2006-01-02")
	snmdate := time.Date(date.Year(), 1, 1, 0, 0, 0, 0, time.Local).AddDate(0, 0, -1).Format("2006-01-02")
	groupBy := strings.Join(repConf.KeyColumns, ",")
	var buff bytes.Buffer
	var hasAcbl, hasBsr, hasBsy, hasBsn bool
	buff.WriteString("INSERT INTO ")
	buff.WriteString(tName)
	buff.WriteString("(")
	for _, col := range repConf.Columns {
		buff.WriteString(col.Name)
		buff.WriteString(",")
		if col.Name == "ACBL" {
			hasAcbl = true
		} else if col.Name == "BSR" {
			hasBsr = true
		} else if col.Name == "BSY" {
			hasBsy = true
		} else if col.Name == "BSN" {
			hasBsn = true
		}
	}
	if !hasAcbl {
		err = fmt.Errorf("生成报表%s的ChangeAnalysis出错，没有配置字段ACBL", repConf.Name)
		return
	}
	buff.Truncate(buff.Len() - 1)
	buff.WriteString(") WITH ")
	if hasBsr {
		buff.WriteString(fmt.Sprintf("sumIf(%s,DTID='%s') AS ACBL_SR,", colName, srdate))
	}
	if hasBsy {
		buff.WriteString(fmt.Sprintf("sumIf(%s,DTID='%s') AS ACBL_SY,", colName, symdate))
	}
	if hasBsn {
		buff.WriteString(fmt.Sprintf("sumIf(%s,DTID='%s') AS ACBL_SN", colName, snmdate))
	}
	buff.WriteString(" SELECT ")
	for _, col := range repConf.Columns {
		if base.InStringSlice(col.Name, repConf.KeyColumns) {
			colExp := col.ColExp
			if colExp == "" {
				colExp = col.Name
			}
			buff.WriteString(colExp)
			buff.WriteString(" AS ")
			buff.WriteString(col.Name)
		} else if col.Name == "ACBL" {
			buff.WriteString(fmt.Sprintf("sumIf(%s,DTID='%s') ACBL", colName, curDate))
		} else if col.Name == "BSR" {
			buff.WriteString("ACBL-ACBL_SR BSR")
		} else if col.Name == "BSY" {
			buff.WriteString("ACBL-ACBL_SY BSY")
		} else if col.Name == "BSN" {
			buff.WriteString("ACBL-ACBL_SN BSN")
		} else {
			if col.ColExp == "" {
				err = fmt.Errorf("生成报表%s的ChangeAnalysis出错，列%s没有定义ColExp", repConf.Name, col.Name)
				return
			}
			buff.WriteString(col.ColExp)
			buff.WriteString(" ")
			buff.WriteString(col.Name)
		}
		buff.WriteString(",")
	}
	buff.Truncate(buff.Len() - 1)
	buff.WriteString(" FROM ")
	buff.WriteString(repConf.DataSource.DFTable)
	buff.WriteString(" WHERE DTID IN (?,?,?,?) AND ")
	buff.WriteString(where)
	buff.WriteString(" GROUP BY ")
	buff.WriteString(groupBy)
	buff.WriteString(" HAVING (ACBL<>0 OR BSR<>0 OR BSY<>0 OR BSN<>0)")
	buff.WriteString(" ORDER BY ABS(BSR) DESC ")
	exists, err = dbHelp.createTable("Memory")
	if err != nil {
		return
	}
	if exists {
		return
	}
	err = base.CHDB.Exec(buff.String(), curDate, srdate, symdate, snmdate).Error
	if err != nil {
		base.CHDB.Exec(fmt.Sprintf("drop table %s", tName))
	}
	return
}

func createDataRangeAnalysis(repConf *Config, tName string, paramVals map[string]interface{}) (err error) {
	if repConf.DataSource.DFTable == "" {
		err = fmt.Errorf("生成报表%s的ChangeAnalysis出错，DataSource.DFTable不能为空", repConf.Name)
		return
	}
	if repConf.DataSource.MFTable == "" {
		err = fmt.Errorf("生成报表%s的ChangeAnalysis出错，DataSource.MFTable不能为空", repConf.Name)
		return
	}
	if repConf.DataSource.TmpTableName == "" {
		err = fmt.Errorf("生成报表%s的ChangeAnalysis出错，DataSource.TmpTableName不能为空", repConf.Name)
		return
	}
	var sdate, edate time.Time
	if paramVals["sdate"] != nil {
		sdate = paramVals["sdate"].(time.Time)
	}
	if sdate.IsZero() {
		err = fmt.Errorf("生成报表%s出错，参数sdate不能为空", repConf.Name)
		return
	}
	if paramVals["edate"] != nil {
		edate = paramVals["edate"].(time.Time)
	}
	if edate.IsZero() {
		err = fmt.Errorf("生成报表%s出错，参数edate不能为空", repConf.Name)
		return
	}
	var where string
	_, where, err = parseLineColumnParams(repConf, paramVals)
	if err != nil {
		return
	}
	paramVals["#where"] = where
	err = createDateRangeData(repConf, tName, paramVals)
	if err != nil {
		base.CHDB.Exec(fmt.Sprintf("drop table %s", tName))
		return
	}
	return
}
